package interpeter;

import interpeter.REPL.RuntimeError;

import java.util.ListIterator;
import java.util.Stack;

//import ast.Func;


public class State
{
	Stack<ActivationRecord> a_stack = new Stack<>();
	
	State() {
		addActivationRecord(); 
	}

	public void addActivationRecord(){
		a_stack.push(new ActivationRecord());
	}
	
	/**
	 * Find a variable by its name (dynamic lookup).
	 */
	Object lookup(String byName)
	{
		ListIterator<ActivationRecord> iter =
				a_stack.listIterator(a_stack.size());
		while (iter.hasPrevious()) {
			ActivationRecord ar = iter.previous();
			if (ar.getValueMap().containsKey(byName))
				return ar.getValueMap().get(byName);
		}
		throw new RuntimeError("undefined variable '" + byName + "'");
	}
	
	@Override
	public String toString()
	{
		return a_stack.peek().toString();
	}

	public ActivationRecord getTopAr() {
		return a_stack.peek();
		
	}
	public void updateVar(String key,Object o){
		getTopAr().getValueMap().put(key, o);
	}
		
	public Object getVarValue(String key){
		return getTopAr().getValueMap().get(key);
	}
}

